import * as c from '@/services/consts';
import { CheckCard, StepsForm } from '@ant-design/pro-components';
import  {
  DrawerForm,
  ProFormDigit,
  ProFormInstance,
  ProFormSelect,
  ProFormSwitch,
  ProFormText,
  ProFormTreeSelect,
} from '@ant-design/pro-form';
import { Col, Divider,  Row, Space,  Tabs, Tag, message } from 'antd';
import TabPane from 'antd/es/tabs/TabPane';
import React, { useEffect, useRef, useState } from 'react';
import { useModel } from 'umi';
import * as api from '@/services/idcOrder';
import { ArrowDownOutlined, ArrowUpOutlined } from '@ant-design/icons';

type VpnServerFormProps = {
  visible: boolean;
  onCancel: () => void;
};

const VpnServerForm: React.FC<VpnServerFormProps> = (props) => {
  const { visible, onCancel } = props;

  if (!visible) {
    return null;
  }

  const formRef = useRef<ProFormInstance>();
  // const formRefDrawer = useRef<ProFormInstance>();

  const [idcRegions, setIdcRegions] = useState<API.IdcRegion[] | undefined>(undefined);
  const [idcOsImages, setIdcOsImages] = useState<API.IdcOsImage[] | undefined>(undefined);
  const [idcSshKeys, setIdcSshKeys] = useState<API.IdcSshKey[] | undefined>(undefined);
  const [idcCatalogs, setIdcCatalogs] = useState<API.IdcProduct[] | undefined>(undefined);
  const [idcOsTypes, setIdcOsTypes] = useState<string[] | undefined>(undefined);
  
  const [selectIdcRegion, setSelectIdcRegion] = useState<string | undefined>(undefined);
  const [selectIdcProduct, setSelectIdcProduct] = useState<API.IdcProduct | undefined>(undefined);
  const [selectIdcOsImage, setSelectIdcOsImage] = useState<API.IdcOsImage | undefined>(undefined);
  const [selectIdcSshKey, setSelectIdcSshKey] = useState<API.IdcSshKey | undefined>(undefined);

  const { supplierOptions, getVpnGroupExTrees } = useModel(
    'useGlobalModel',
    (model) => ({
      supplierOptions: model.supplierOptions,
      getVpnGroupExTrees: model.getVpnGroupExTrees,
    }),
  );

  const loadGroupTreeData = async (params: any) => {
    const treeData = getVpnGroupExTrees(params?.productId);

    return Promise.resolve(treeData);
  };

  
  const loadIdcCatalogs = async (region:string) => { 
    let resultCatalogs = await api.catalogs({region});
    if (resultCatalogs && resultCatalogs.success === true) {
      setIdcCatalogs(resultCatalogs.data);
      console.log(resultCatalogs.data);
    }
  };
  
  const loadIdcOsImages = async (region:string, type?: string) => {   
    let resultOs = await api.osimages({region,type});
    if (resultOs && resultOs.success === true) {
      setIdcOsImages(resultOs.data);
      console.log(resultOs.data);
      let tabs = [];
      for(let d of resultOs.data){
        if(d.region != selectIdcRegion || d.status != 'active') continue;
        if(tabs.indexOf(d.user) == -1){
          tabs.push(d.user);
        }
      }
      setIdcOsTypes(tabs);
    }
  };

  
  const loadIdcSshKeys = async (region:string) => {
    let resultSshKeys = await api.sshkeys({region});
    if (resultSshKeys && resultSshKeys.success === true) {
      setIdcSshKeys(resultSshKeys.data);
      console.log(resultSshKeys.data);
    }
  };
  
  const loadRegions = async () => {
    let result = await api.regions();
    if (result && result.success === true) {
      setIdcRegions(result.data);
      console.log(result.data);
    }
  };
  
  useEffect(() => {
    loadRegions();
  }, []);



  const handleFormSubmit = async (record: API.IdcOrderConfigForm) => {
    record.idcBilling = 'hour';
    record.idcProductId = selectIdcProduct.id;
    record.idcOsImageId = selectIdcOsImage.id;
    record.idcSshKeyId = selectIdcSshKey.id;
    record.idcType = 'ovh';
    record.orderType = c.IdcOrderType.PublicCloud.value;
    record.idcRegion = selectIdcRegion;
    // console.log(record);
    // return;
    let result = await api.add({ ...record });

    if (result && result.success === true) {
      onCancel();
    }
  };


  return (
    
      <StepsForm<API.IdcOrderConfigForm>
        stepsProps={{
          direction: 'vertical',
        }}
        onFinish={async (values) => {
          console.log(values);
          // await waitTime(5000);
          await handleFormSubmit(values)
        }}
        formRef={formRef}
        formProps={{
          validateMessages: {
            required: '此项为必填项',
          },
        }}
        containerStyle={{marginLeft:-50, marginTop:-50,minHeight:500}}
        stepsFormRender={(dom, submitter) => {
          return (
            <DrawerForm<API.IdcOrderConfigForm>
              open={visible}
              title={`购买服务器`}
              // formRef={formRefDrawer}
              // autoFocusFirstInput
              width={1224}
              // onFinish={handleFormSubmit}
              drawerProps={{
                // forceRender: true,
                // destroyOnClose: true,
                // closable: false,
                onClose: onCancel,
                maskClosable: false,
              }}
              submitter={{
                render: (props, defaultDoms) => {
                  return submitter;//[defaultDoms[0]];
                },
              }}
            >
              {dom}
            </DrawerForm>
          );
        }}
      >
        <StepsForm.StepForm
          name="idc_regions"
          title={selectIdcRegion ? selectIdcRegion : '选择区域'}
          onFinish={async () => {
            console.log(formRef.current?.getFieldsValue());
            // return true;
            console.log(selectIdcRegion);
            if(selectIdcRegion){              
              await loadIdcCatalogs(selectIdcRegion);
              await loadIdcSshKeys(selectIdcRegion);
              return true;
            }
            else{
              message.error("请选择区域");
              return false;
            }
          }}
        >
          <Space style={{width:1020}}>
            <Row gutter={24}>
            <Col span={24}>
            <Divider orientation="left" orientationMargin={0}>选择区域</Divider>
            </Col>
            <Col span={24}>
            <CheckCard.Group
              onChange={(value) => {
                console.log('value', value);
                setSelectIdcRegion(value ? `${value}` : undefined);
              }}
              size='small'
              key='groupRegion'
              loading={!idcRegions}
            >
              {idcRegions?.map((val)=>{
                return <CheckCard title={val.regionCode} description="" value={val.regionCode} />  
              })}
            </CheckCard.Group>
            
          </Col>
          <Col span={24}>
          <Divider orientation="left" orientationMargin={0}></Divider>
          </Col></Row>
          </Space>
        </StepsForm.StepForm>

        <StepsForm.StepForm
          name='stepCatalog'
          title="产品信息"
          // style={{marginTop:-30, marginLeft:-80}}
          onFinish={async () => {
            console.log(formRef.current?.getFieldsValue());
            if(selectIdcProduct){
              await loadIdcOsImages(selectIdcRegion,selectIdcProduct.osType)
              return true;
            }
            else{
              message.error("请选择产品");
              return false;
            }
          }}
        >
          <Space style={{width:1000}}>
          <Row gutter={24}>
            <Col span={24}>
              <Divider orientation="left" orientationMargin={0}>选择产品 {idcCatalogs && idcCatalogs.length > 0 && idcCatalogs[0]?.pricings && idcCatalogs[0]?.pricings.length > 0 
              ? <Tag color='blue'>价格单位：{idcCatalogs[0]?.pricings[0].currencyCode}</Tag> : ''}</Divider>
            </Col>
            <Col span={24}>
            <CheckCard.Group
              onChange={(value) => {
                console.log('value', value);
                setSelectIdcProduct(value);
              }}
              size='small'
              key='groupProduct'
              loading={!idcCatalogs}
            >
              {idcCatalogs?.map((val)=>{
                return <CheckCard title={val.name} value={val} style={{width:125}} description={<>
                <div><Tag>{val.osType}</Tag></div>
                <div>CPU: {val.cpus}核</div>
                <div>内存: {val.ram / 1000}G</div>
                <div>硬盘: {val.disk}G</div>
                <div>带宽: {val.outboundBandwidth >= 1000 ? `${val.outboundBandwidth / 1000}G` : `${val.outboundBandwidth}M`}</div>
                {/* <div>带宽: <ArrowDownOutlined />{val.inboundBandwidth >= 1000 ? `${val.inboundBandwidth / 1000}G` : `${val.inboundBandwidth}M` } 
                <ArrowUpOutlined />{val.outboundBandwidth >= 1000 ? `${val.outboundBandwidth / 1000}G` : `${val.outboundBandwidth}M`}</div> */}
                {val.pricings?.map((vp) => {return vp.price > 0 ? <div>{vp.intervalUnit}: {vp.price / 100000000}</div> : <div>{vp.intervalUnit}: --</div>})}
                </>}/>  
              })}
            </CheckCard.Group>
          </Col>
          <Col span={24}>
          <Divider orientation="left" orientationMargin={0}></Divider>
          </Col></Row>
          </Space>
        </StepsForm.StepForm>

        <StepsForm.StepForm
          name="stepOs"
          title="操作系统"
          onFinish={async () => {
            // console.log(formRef.current?.getFieldsValue());
            // return true;
            if(selectIdcOsImage){
              if(selectIdcSshKey){
                return true;
              }
              else{
                message.error("请选择SSH Key");
                return false;
              }
            }
            else{
              message.error("请选择操作系统");
              return false;
            }
          }}
        >
          <Space style={{width:1000}}>
            <Row gutter={24}>
            <Col span={24}>
            <Divider orientation="left" orientationMargin={0}>安装系统</Divider>
            </Col>          
            <Col span={24}>
            <CheckCard.Group
              onChange={(value) => {
                console.log('value', value);
                setSelectIdcOsImage(value);
              }}
              size='small'
              key={`groupOsimages`}
              loading={!idcOsImages}
            >
            <Tabs type='card'>
            {idcOsTypes?.map((val)=>{
              return <TabPane key={val} tab={val}>
                  {idcOsImages?.map((vo)=>{
                    return vo.user != val || vo.region != selectIdcRegion ? <></> :
                     <CheckCard title={vo.name} value={vo} description=''/>  
                  })}
              </TabPane>
            })}
            </Tabs>
          </CheckCard.Group></Col>
          
          <Col span={24}>
            <Divider orientation="left" orientationMargin={0}>登录 SSH KEY</Divider>
          </Col>
          
          <Col span={24}>
            <CheckCard.Group
              onChange={(value) => {
                console.log('value', value);
                setSelectIdcSshKey(value);
              }}
              size='small'
              key={`groupSshKey`}
              loading={!idcSshKeys}
              style={{width:900}}
            >
              {idcSshKeys?.map((vo)=>{
                return <CheckCard title={vo.name} value={vo} description=''/>  
              })}
            </CheckCard.Group>
          </Col>
          <Col span={24}>
            <Divider orientation="left" orientationMargin={0}></Divider>
          </Col>
          </Row>
          </Space>
        </StepsForm.StepForm>

        <StepsForm.StepForm<API.IdcOrderConfigForm>
          name='stepVpnServer'
          title="实例设置"
        >
          <Space style={{width:1000}}>
          <Row gutter={24} style={{width:1000}}>
            <Col span={24}>
            <Divider orientation="left" orientationMargin={0}>购买产品信息</Divider>
            </Col> 
    
    
            <Col span={4}>区域：{selectIdcRegion}</Col>
            <Col span={4}>产品：{selectIdcProduct?.name}</Col>
            <Col span={4}>支付：时付</Col>
            <Col span={4}>价格：{selectIdcProduct?.pricings?.map((val)=> val.intervalUnit == 'hour' ? <>{val.price / 100000000} {val.currencyCode}</> : '')}</Col>
            <Col span={4}>系统：{selectIdcOsImage?.name}</Col>
            <Col span={4}>SSH Key：{selectIdcSshKey?.name}</Col>


            <Col span={24}>
            <Divider orientation="left" orientationMargin={0}></Divider>
            </Col> 
            <Col span={4}>
              <ProFormDigit
                name='quantity'
                label="购买数量"
                min={1}
                max={1000}
                rules={[{ required: true, message: '请输入购买数量' }]}
              />
            </Col> 
            <Col span={4}>
              <ProFormText
                name='idcServerName'
                label="服务器名称"
                rules={[{ required: true, message: '请输入服务器名称' }]}
              />
            </Col>

            <Col span={24}>
            <Divider orientation="left" orientationMargin={0}>实例信息设置</Divider>
            </Col> 
            <Col span={12}>
              <ProFormTreeSelect
                name="serverGroupIds"
                label="分组"
                placeholder="请选择分组"
                allowClear={false}
                // secondary
                rules={[{ required: true, message: '请选择分组' }]}
                request={loadGroupTreeData}
                // tree-select args
                fieldProps={{
                  showArrow: true,
                  showSearch: true,
                  treeCheckable: true,
                  maxTagCount: 1,
                  multiple: true,
                  treeDefaultExpandAll: true,
                  listHeight: 600,
                  treeNodeLabelProp: 'title',
                  filterTreeNode: (input, option) =>
                    option && option.title
                      ? option.title
                          .toString()
                          .toLowerCase()
                          .indexOf(input.toLowerCase()) >= 0
                      : false,
                }}
              />
            </Col>          
            <Col span={12}>
              <ProFormSwitch
                name="serverStatus"
                label="状态"
                initialValue={true}
                fieldProps={{
                  defaultChecked: true,
                }}
              />
            </Col>


            <Col span={4}>
              <ProFormDigit
                name="instanceIdStart"
                label="起始实例ID"
                min={1}
                max={2099999999}
                rules={[{ required: true, message: '请输入起始实例ID' }]}
                placeholder="请输入起始实例ID"
              />
            </Col>
            <Col span={4}>
              <ProFormText
                name="serverNamePrefix"
                label="实例名称前缀"
                // rules={[{ required: true, message: '请输入实例名称前缀' }]}
              />
            </Col>
            <Col span={4}>
              <ProFormText
                name="serverNameSuffix"
                label="实例名称后缀"
                // rules={[{ required: true, message: '请输入实例名称前缀' }]}
              />
            </Col>
            <Col span={4}>
              <ProFormSelect
                name="serverType"
                label="服务器类型"
                placeholder="请选择服务器类型"
                allowClear={true}
                options={c.ServerTypes}
              />
            </Col>
            <Col span={4}>
              <ProFormSelect
                name="serverSupplier"
                label="服务器供应商"
                placeholder="请选择服务器供应商"
                allowClear={true}
                options={supplierOptions}
                fieldProps={{
                  showArrow: true,
                  showSearch: true,
                }}
              />
            </Col>  
            <Col span={4}>
            </Col>


            <Col span={4}>
              <ProFormDigit
                name="serverPort"
                label="服务端口"
                min={1}
                max={65535}
                rules={[{ required: true, message: '请输入服务端口' }]}
                placeholder="请输入服务端口"
              />
            </Col>
            <Col span={4}>
              <ProFormDigit
                name="serverPingPort"
                label="测速端口"
                min={0}
                max={65535}
                rules={[{ required: true, message: '请输入测速端口' }]}
                placeholder="请输入测速端口"
              />
            </Col>
            <Col span={4}>
              <ProFormDigit
                name="serverMaxUser"
                label="用户限制"
                min={0}
                max={10000}
                rules={[{ required: true, message: '请输入用户限制' }]}
                placeholder="最大在线用户数量"
                initialValue={0}
              />
            </Col>
            <Col span={4}>
              <ProFormDigit
                name="serverMaxBandwidth"
                label="总带宽限制"
                min={0}
                max={102400}
                rules={[{ required: true, message: '请输入带宽限制' }]}
                placeholder="服务器最大带宽"
                addonAfter={<span className="ant-form-item-extra">MB</span>}
                initialValue={0}
              />
            </Col>
            <Col span={4}>
              <ProFormDigit
                name="serverMaxUserBandwidth"
                label="用户带宽限制"
                min={0}
                max={102400}
                rules={[{ required: true, message: '请输入用户带宽限制' }]}
                placeholder="用户最大带宽"
                addonAfter={<span className="ant-form-item-extra">KB</span>}
                initialValue={0}
              />
            </Col>
            <Col span={4}>
              <ProFormText
                name='serverPrice'
                label="价格"
                placeholder="请输入价格"
              />
            </Col>
            
            <Col span={24}>
              <Divider orientation="left" orientationMargin={0}></Divider>
            </Col>
          </Row>
          </Space>
        </StepsForm.StepForm>
        
      </StepsForm>








    // </DrawerForm>
  );
};

export default VpnServerForm;
